<?php
@header('Content-Type: text/html; charset=UTF-8');
@ignore_user_abort(true);
@set_time_limit(0);
require_once __DIR__ . '/vcode.php';

$mysql = require_once __DIR__ . '/../application/index/database.php';
try {
    $pdo = new PDO("mysql:host={$mysql['hostname']};dbname={$mysql['database']};port={$mysql['hostport']}", $mysql['username'], $mysql['password']);
} catch (Exception $e) {
    exit('链接数据库失败:' . $e->getMessage());
}
$pdo->exec("set names utf8");

$keyRow = $pdo->query("select value from dg_configs where vkey='cronkey' limit 1")->fetchColumn();
$key = isset($_GET['key']) ? $_GET['key'] : null;
if (!($keyRow && $key && $key == $keyRow)) {
    exit('监控识别码不正确！');
}

$loginRow = $pdo->query("select value from dg_configs where vkey='login_api' limit 1")->fetchColumn();
if ($loginRow) {
    define("LOGIN_API", $loginRow);
} else {
    define("LOGIN_API", 'http://' . $_SERVER['HTTP_HOST'] . '/qlogin/login.php');
}

$stmt = $pdo->query("SELECT
	qid,
	uin,
	MD5(pwd) AS pwd
FROM
	dg_qqs
WHERE
	cookiezt = 1
AND autotime > NOW()
ORDER BY
	lastauto ASC
LIMIT 3
");
$num = 0;
while ($row = $stmt->fetch()) {
	$num++;
    $uin = $row['uin'];
    $pwd = $row['pwd'];
    $qid = $row['qid'];
    $pdo->exec("update dg_qqs set lastauto=NOW() where qid='{$qid}' limit 1");
    echo autoUpdate($uin, $pwd, $qid);
}

echo "<br>总共执行{$num}个QQ。";

function autoUpdate($uin, $pwd, $qid)
{
    echo "{$uin}:";
    $checkUrl = "http://check.ptlogin2.qq.com/check?pt_tea=2&uin={$uin}&appid=549000929&ptlang=2052&regmaster=&pt_uistyle=9&r=0." . time();
    $json = get_curl($checkUrl);
    $json = str_replace(array('ptui_checkVC(\'', '\');'), array('', ''), $json);
    $arr = explode('\',\'', $json);
    if (isset($arr[1]) && strlen($arr[1]) == 4) {
        //无验证码直接更新
        return update($uin, $pwd, $qid, $arr[1], $arr[3]);
    } elseif (isset($arr[1])) {
        $cap_cd = $arr[1];
        $cap_union_new_show = "http://captcha.qq.com/cap_union_new_show?aid=549000929&captype=&protocol=http&clientype=1&disturblevel=&apptype=2&noheader=0&uid={$uin}&color=&showtype=&cap_cd={$cap_cd}&rnd=629052";
        $get = get_curl($cap_union_new_show);
        if (preg_match('/,T="([a-zA-Z0-9\.\*\?\_\-]{121})"/i', $get, $arr)) {
            $vsig = $arr[1];
            $cap_union_new_getcapbysig = "http://captcha.qq.com/cap_union_new_getcapbysig?aid=549000929&captype=&protocol=http&clientype=1&disturblevel=&apptype=2&noheader=0&uid={$uin}&color=&showtype=&cap_cd={$cap_cd}&rnd=629052&rand=0." . time() . "&vsig={$vsig}&ischartype=1";
            $img = get_curl($cap_union_new_getcapbysig);
            $json = getCode($img);
            $reArray = json_decode($json, true);
            if (isset($reArray['info']) && $reArray['info'] == 1) {
                $code = $reArray['result'];
                $cap_union_new_verify = "http://captcha.qq.com/cap_union_new_verify";
                $post = "aid=549000929&captype=&protocol=http&clientype=1&disturblevel=&apptype=2&noheader=0&uid={$uin}&color=&showtype=&cap_cd={$cap_cd}&rnd=468333&rand=0." . time() . "&subcapclass=0&vsig={$vsig}&ans={$code}&";
                $json = get_curl($cap_union_new_verify, $post);
                $arr = json_decode($json, true);
                if (isset($arr['errorCode']) && $arr['errorCode'] == 0) {
                    return update($uin, $pwd, $qid, strtoupper($arr['randstr']), $arr['ticket']);
                } else {
                    errorCode($reArray['imgId']);
                    return "打码错误";
                }
            } else {
                return "打码失败:" . $json;
            }
        } else {
            return "ERROR! Not found T";
        }
    } else {
        echo "ERROR!{$json}";
    }

    echo "<br>";
}

function update($uin, $pwd, $qid, $vcode, $pt)
{
    global $pdo;

    $v1 = strpos('s' . $vcode, '!') ? 0 : 1;
    $type = $v1 ? '【打码】' : '【无码】';
    $pUrl = "http://115.28.65.24:8866/?action=getp&uin={$uin}&code={$vcode}&pwd={$pwd}&r=" . time();
    $json = get_curl($pUrl);
    $arr = json_decode($json, true);
    if (!(isset($arr['code']) && $arr['code'] == 0)) {
        return "获取P值失败";
    }
    $p = $arr['p'];

    $url = "http://ptlogin2.qq.com/login?verifycode={$vcode}&u={$uin}&p={$p}&pt_randsalt=2&ptlang=2052&low_login_enable=0&u1=https%3A%2F%2Fh5.qzone.qq.com%2Fmqzone%2Findex&from_ui=1&fp=loginerroralert&device=2&aid=549000929&daid=5&pt_ttype=1&pt_3rd_aid=0&ptredirect=1&h=1&g=1&pt_uistyle=9&pt_vcode_v1={$v1}&pt_verifysession_v1={$pt}&";
    $url = base64_encode($url);
    $json = get_curl(LOGIN_API, "url={$url}");
    $arr = json_decode($json, true);
    if (!isset($arr['code'])) {
        if (preg_match("/ptuiCB\('(\d+)'/i", $json, $arr)) {
            if (in_array($arr[1], array(3, 12, 17, 19))) {
                $pdo->exec("update dg_qqs set cookiezt='{$arr[1]}' where qid='{$qid}' limit 1");
            }
        }
        return $json . $type;
    }

    $skey = $arr['skey'];
    $p_skey = $arr['p_skey'];
    $pdo->exec("update dg_qqs set skey='{$skey}',p_skey='{$p_skey}',cookiezt=0 where qid='{$qid}' limit 1");

    return "更新成功" . $type;
}


function get_curl($url, $post = 0, $referer = 0, $cookie = 0, $header = 0, $ua = 0, $nobaody = 0)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $klsf[] = "Accept:*/*";
    $klsf[] = "Accept-Encoding:gzip,deflate,sdch";
    $klsf[] = "Accept-Language:zh-CN,zh;q=0.8";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $klsf);
    if ($post) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }
    if ($header) {
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
    }
    if ($cookie) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    if ($referer) {
        if ($referer == 1) {
            curl_setopt($ch, CURLOPT_REFERER, "http://m.qzone.com/infocenter?g_f=");
        } else {
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }
    }
    if ($ua) {
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
    } else {
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; U; Android 4.0.4; es-mx; HTC_One_X Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0');
    }
    if ($nobaody) {
        curl_setopt($ch, CURLOPT_NOBODY, 1);//主要头部
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//跟随重定向
    }
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $ret = curl_exec($ch);
    curl_close($ch);
    return $ret;
}
